<template>
	<!-- 展示二维码 -->
	<view @click="$emit('cancel')" class="cu-modal" :class="show ?'show':''">
		<view style="width: 560upx;" class="cu-dialog">
			<view style="position: relative;" class="cu-bar bg-white justify-center ">
				<text class="text-bold lg">{{label || '加群领取绘本'}}</text>
				<view  style="position: absolute;right: 30upx;top:30upx" @click.stop="$emit('cancel')">
					<text class="cuIcon-close text-gray"></text>
				</view>
			</view>
			<view @click.stop="saveFn"  class="padding-lr bg-white">
				<view class="bg-img" style="height:500upx;"
					:style="{backgroundImage:'url('+value+')'}">
				</view>
			</view>
			<view @click.stop="saveFn" class="padding bg-white text-center">点击下载</view>
		</view>
	</view>
</template>

<script>
	
	import {
		tokenKey
	} from '@/config/index.js'
	
	export default{
		props:{
			show:Boolean,
			value:String,
			label:String
		},
		methods:{
			// 保存图片
			saveFn() {
				if (!this.value) return false;
				// 验证权限
				// #ifdef MP
				uni.authorize({
					scope: 'scope.writePhotosAlbum',
					success: () => {
						this.saveMainFn();
					},
					fail: () => {
						uni.showModal({
							content: '检测到您没打开保存图片功能权限，是否去设置打开？',
							confirmText: "确认",
							cancelText: '取消',
							success: res => {
								if (res.confirm) {
									uni.openSetting({
										success: res => {
											if (res.authSetting[
													'scope.writePhotosAlbum']) {
												this.saveMainFn();
											}
										}
									})
								} else {
									return false;
								}
							}
						})
					}
				})
				// #endif
			},
			getImageFn() {
				let header = {};
				header[tokenKey] = this.$store.state.userInfo.accessToken;
				return new Promise((reslove, reject) => {
					uni.request({
						url: this.value,
						header,
						responseType: 'arraybuffer',
						success: (res) => reslove(res),
						fail: () => reject(new Error("图片下载失败"))
					})
				})
			},
			writeFile(val) {
				let base = uni.arrayBufferToBase64(val)
				let url = this.value;
				let type = url.slice(url.lastIndexOf('.'));
				let filePath = `${wx.env.USER_DATA_PATH}/${Date.now()}${type}`;
				return new Promise((reslove, reject) => {
					uni.getFileSystemManager().writeFile({
						filePath: filePath, //创建一个临时文件名
						data: base, //写入的文本或二进制数据
						encoding: 'base64', //写入当前文件的字符编码
						success: res => reslove(filePath),
						fail: err => reject(new Error("图片写入失败"))
					})
				})
			},
			saveImageToPhotosAlbum(filePath) {
				return new Promise((reslove, reject) => {
					uni.saveImageToPhotosAlbum({
						filePath: filePath,
						success: () => reslove(),
						fail: () => reject(new Error("图片保存失败"))
					})
				})
			},
			
			
			async saveMainFn() {
				uni.showLoading({
					title: "图片下载中"
				})
				try {
					let res = await this.getImageFn();
					let filePath=await this.writeFile(res.data);
					await this.saveImageToPhotosAlbum(filePath)
					this.showModalFn(new Error('保存成功'));
				} catch (err) {
					this.showModalFn(err);
				} finally {
					this.$emit('cancel');
					uni.hideLoading();
				}
			
			},
			// 弹窗
			showModalFn(err) {
				uni.showModal({
					content: err.message,
					showCancel: false
				})
			},
		}
	}
</script>

<style>
</style>